<template>
	<view>
		<!-- 顶部栏 -->
		<view class="top">
			<navigator url="/pages/zwj/cheliangweixiu/cheliangweixiu">
				<image class="back" src="/static/images/白色左箭头.png"></image>
			</navigator>
			<view class="title">立即预约</view>
		</view>

		<!-- 主表单区域 -->
		<view style="margin-top: -220rpx;">
			<uni-card>
				<uni-forms ref="baseForm" :modelValue="baseFormData" labelWidth="100px">

					<!-- 维修方式 -->
					<view class="itemTitle">维修方式</view>
					<uni-forms-item name="repairWay">
						<uni-data-checkbox v-model="baseFormData.repairWay" :localdata="repairTypeOptions" />
					</uni-forms-item>

					<!-- 客户信息 -->
					<view class="itemTitle">客户信息</view>
					<u-line margin="20rpx 0rpx 30rpx 0rpx" />
					<uni-forms-item label="车主姓名" name="userName" required>
						<uni-easyinput v-model="userName" placeholder="请输入车主姓名" />
					</uni-forms-item>
					<uni-forms-item label="联系方式" name="phone" required>
						<uni-easyinput v-model="phone" placeholder="请输入联系方式" />
					</uni-forms-item>
					<uni-forms-item label="预约时间" name="repairTime" required>
						<uni-datetime-picker type="datetime" v-model="baseFormData.repairTime" :clear-icon="false"
							placeholder="请选择预约时间" />
					</uni-forms-item>
					<uni-forms-item label="取车位置" name="location" v-if="baseFormData.repairWay === 0" required>
						<uni-easyinput v-model="baseFormData.location" placeholder="请输入取车位置" />
					</uni-forms-item>

					<!-- 车辆类型 -->
					<view class="itemTitle">车辆类型</view>
					<u-line margin="20rpx 0rpx 30rpx 0rpx" />
					<uni-forms-item label="车辆品牌" name="carBrand" required>
						<uni-data-select v-model="baseFormData.carBrand" :localdata="carBrandList" placeholder="请选择" />
					</uni-forms-item>
					<uni-forms-item label="车牌号" name="carNumber" required>
						<uni-data-select v-model="selectedCarNumber" :localdata="carNumberList" placeholder="请选择"
							@change="onCarNumberChange" />
					</uni-forms-item>

					<!-- 照片 -->
					<view class="itemTitle">照片</view>
					<u-line margin="20rpx 0rpx 30rpx 0rpx"></u-line>
					<uni-forms ref="baseForm" :modelValue="baseFormData">
						<uni-forms-item label="维修部位照片" required>
							<view class="img-row">
								<view class="img-upload" @click="uploadImg('ve')">
									<image v-if="baseFormData.vehiclePhotos" :src="baseFormData.vehiclePhotos"
										class="img" />
									<view v-else class="img-placeholder">+<br />上传照片</view>
								</view>
							</view>
						</uni-forms-item>
						<uni-forms-item label="整车照片" required>
							<view class="img-row">
								<view class="img-upload" @click="uploadImg('repair')">
									<image v-if="baseFormData.repairPhotos" :src="baseFormData.repairPhotos"
										class="img" />
									<view v-else class="img-placeholder">+<br />上传照片</view>
								</view>
							</view>
						</uni-forms-item>
					</uni-forms>
				</uni-forms>
			</uni-card>
		</view>

		<!-- 提交按钮 -->
		<view class="sub">
			<u-button type="primary" size="large" text="提交预约" @click="submitForm" />
		</view>
	</view>
</template>

<script>
	import request from '../../../uitls/request';
	import uploadFile from '../../../uitls/uploadFile.js';
	export default {
		data() {
			return {
				uid: '',
				merchantId: '',
				userName: '',
				phone: '',
				selectedCarNumber: '', // 当前选中的车牌号（carInfoId）

				carBrandList: [], // 品牌下拉选项
				carNumberList: [], // 车牌号下拉选项
				fullCarList: [], // 完整车辆信息列表

				baseFormData: {
					userId: '',
					repairTime: '',
					location: '',
					carInfoId: '',
					repairWay: 0,
					vehiclePhotos: '',
					repairPhotos: '',
					reservationTime: '',
					repairId: ''
				},

				carBrand: [{
						id: 1,
						name: '奥迪'
					},
					{
						id: 2,
						name: '红旗'
					},
					{
						id: 4,
						name: '大众'
					},
					{
						id: 5,
						name: '比亚迪'
					}
				],

				repairTypeOptions: [{
						text: '到店维修',
						value: 1
					},
					{
						text: '上门取车',
						value: 0
					}
				]
			};
		},

		methods: {
			submitForm() {
				const {
				    repairTime,
				    carInfoId,
				    vehiclePhotos,
				    repairPhotos,
				    location,
				    repairWay
				  } = this.baseFormData;
				
				  // 手动校验必填字段
				  if (!repairTime) {
				    return uni.showToast({ title: '请选择预约时间', icon: 'none' });
				  }
				  if (!carInfoId) {
				    return uni.showToast({ title: '请选择车牌号', icon: 'none' });
				  }
				  if (!vehiclePhotos) {
				    return uni.showToast({ title: '请上传维修部位照片', icon: 'none' });
				  }
				  if (!repairPhotos) {
				    return uni.showToast({ title: '请上传整车照片', icon: 'none' });
				  }
				  if (repairWay === 0 && !location) {
				    return uni.showToast({ title: '请输入取车位置', icon: 'none' });
				  }
				const randomStr = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
				const timestamp = new Date();
				const repairId =
					`R${timestamp.getFullYear()}${(timestamp.getMonth() + 1).toString().padStart(2, '0')}${timestamp.getDate().toString().padStart(2, '0')}${randomStr}`;

				// 生成预约时间字符串
				const formatTime = (date) => {
					const pad = (n) => n.toString().padStart(2, '0');
					return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
				};
				const reservationTime = formatTime(timestamp);

				// 将生成的字段填入表单数据
				this.baseFormData.repairId = repairId;
				this.baseFormData.reservationTime = reservationTime;
				const dataToSend = {
					...this.baseFormData,
					merchantid: this.merchantId,
					status: 0
				};
				console.log(this.baseFormData)
				request({
					url: '/evaluate/reservation',
					method: 'POST',
					data: dataToSend,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.showToast({
								title: '预约成功',
								icon: 'success'
							});
							uni.setStorageSync('reservationData', dataToSend);
							uni.redirectTo({
								url: '/pages/zwj/yuyuechenggong/yuyuechenggong'
							});
						} else {
							uni.showToast({
								title: '提交失败',
								icon: 'none'
							});
						}
					}
				});
			},

			getCarList() {
				request({
					url: '/bigbase/carInfo/list',
					data: {
						uid: this.uid
					},
					method: 'GET',
					success: (res) => {
						const carList = res.data.rows || [];
						// 存储完整列表
						this.fullCarList = carList;

						// 构造下拉列表数据
						this.carNumberList = carList.map(item => ({
							value: item.id,
							text: item.carNum
						}));

						const ownedBrandIds = [...new Set(carList.map(item => item.brand))];
						this.carBrandList = this.carBrand
							.filter(brand => ownedBrandIds.includes(brand.id))
							.map(brand => ({
								value: brand.id,
								text: brand.name
							}));
					}
				});
			},

			onCarNumberChange(carInfoId) {
				const selectedCar = this.fullCarList.find(car => car.id === carInfoId);
				if (selectedCar) {
					this.baseFormData.carInfoId = selectedCar.id;
				}
			},
			uploadImg(key) {
				uploadFile({
					success: (urls) => {
						const url = Array.isArray(urls) ? urls[0] : urls;
						if (key === 'repair') {
							this.baseFormData.repairPhotos = url;
						} else if (key === 've') {
							this.baseFormData.vehiclePhotos = url;
						}
						console.log('上传成功 URL:', url);
					},
					fail: (err) => {
						console.error('上传失败:', err);
						uni.showToast({
							title: '图片上传失败',
							icon: 'none'
						});
					}
				});
			}

		},

		onLoad(options) {
			this.merchantId = options.id;
			const userInfo = uni.getStorageSync('userInfo');
			this.userName = userInfo.userName;
			this.phone = userInfo.phone;
			this.baseFormData.userId = userInfo.id;
			this.uid = userInfo.id;
			this.getCarList();
		}
	};
</script>

<style>
	.top {
		width: 100%;
		padding-bottom: 120px;
		background: url(../../../static/images/组 8.png) no-repeat;
		background-size: cover;
	}

	.top .back {
		position: absolute;
		margin-left: 20px;
		margin-top: 30px;
		width: 15px;
		height: 15px;
		z-index: 2;
	}

	.top .title {
		text-align: center;
		font-size: 18px;
		color: #fff;
		padding-top: 25px;
		margin-bottom: 30rpx;
	}

	.itemTitle {
		font-size: 30rpx;
		font-weight: bold;
		margin: 20rpx 0;
	}

	.sub {
		height: 160rpx;
		width: 70%;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-left: auto;
		margin-right: auto;
	}

	.img-row {
		display: flex;
		flex-direction: row;
		gap: 24rpx;
		margin-bottom: 20rpx;
	}

	.img-upload {
		width: 150rpx;
		height: 150rpx;
		background: #f5f6fa;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		border: 2rpx dashed #e0e0e0;
		overflow: hidden;
	}

	.img-placeholder {
		color: #bbb;
		font-size: 32rpx;
		text-align: center;
		line-height: 44rpx;
	}

	.img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}
</style>